#include "widget.h"
#include "ui_widget.h"
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QString>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    QStringList portName;
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
        portName << info.portName();
    }
    ui->portID->addItems(portName);
    sp = new QSerialPort();

    connect(sp,SIGNAL(readyRead()),this,SLOT(readyReadSlot()));

}


void Widget::readyReadSlot(){
    QString buf;
    buf = QString(sp->readAll());
    ui->recv_box->appendPlainText(buf);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_open_clicked()
{
    QSerialPort::BaudRate bd;
    QSerialPort::DataBits db;
    QSerialPort::StopBits sb;
    QSerialPort::Parity pt;

    switch (ui->baudrate->currentIndex()) {
        case 0:bd = QSerialPort::Baud9600;break;
        case 1:bd = QSerialPort::Baud4800;break;
        case 2:bd = QSerialPort::Baud115200;break;
    }
    switch (ui->databit->currentIndex()) {
        case 0:db = QSerialPort::Data8;break;
        case 1:db = QSerialPort::Data5;break;
        case 2:db = QSerialPort::Data6;break;
        case 3:db = QSerialPort::Data7;break;
    }
    switch (ui->stopbit->currentIndex()) {
        case 0:sb = QSerialPort::OneStop;break;
        case 1:sb = QSerialPort::OneAndHalfStop;break;
        case 2:sb = QSerialPort::TwoStop;break;
    }
    switch (ui->parity->currentIndex()) {
        case 0:pt = QSerialPort::NoParity;break;
        case 1:pt = QSerialPort::EvenParity;break;
        case 2:pt = QSerialPort::OddParity;break;
    }

    sp->setPortName(ui->portID->currentText());
    sp->setBaudRate(bd);
    sp->setDataBits(db);
    sp->setStopBits(sb);
    sp->setParity(pt);

    if(sp->open(QIODevice::ReadWrite)){
        QMessageBox::information(this,"提示","成功");
    }
    else{
        QMessageBox::warning(this,"警告","失败");
    }
}

void Widget::on_close_clicked()
{
    sp->close();
}

void Widget::on_send_clicked()
{
    sp->write(ui->send_box->text().toUtf8().data());
}

void Widget::on_clear_clicked()
{
    ui->recv_box->clear();
}
